package controllers

import (
	beego "github.com/beego/beego/v2/server/web"
	"rk9/models"
)

type UserController struct {
	beego.Controller
}
type Msg struct {
	Code int
	Msg  string
	Data interface{}
}

func (c *UserController) List() {
	page, _ := c.GetInt("page", 1)
	size, _ := c.GetInt("size", 5)
	offset := (page - 1) * size
	var alluser []models.User
	err := models.DB.Debug().Offset(offset).Where("id= ?", "desc").Limit(size).Find(&alluser).Error
	if err != nil {
		res := Msg{
			Code: 0,
			Msg:  "查询失败",
			Data: nil,
		}
		c.Data["json"] = res
		c.ServeJSON()
	} else {
		res := Msg{
			Code: 200,
			Msg:  "查询成功",
			Data: alluser,
		}
		c.Data["json"] = res
		c.ServeJSON()
	}
}
func (c *UserController) Update() {
	id, _ := c.GetInt("ing")
	img := c.GetString("img")
	name := c.GetString("name")
	tel := c.GetString("tel")
	types := c.GetString("types")
	come := c.GetString("come")
	price, _ := c.GetFloat("price")
	score := c.GetString("score")

	user := models.User{
		Img:   img,
		Name:  name,
		Tel:   tel,
		Types: types,
		Come:  come,
		Price: price,
		Score: score,
	}
	err := models.DB.Debug().Where("id=?", id).Updates(&user).Error
	if err != nil {
		res := Msg{
			Code: 0,
			Msg:  "修改失败",
			Data: nil,
		}
		c.Data["json"] = res
		c.ServeJSON()
	} else {
		res := Msg{
			Code: 200,
			Msg:  "修改成功",
			Data: nil,
		}
		c.Data["json"] = res
		c.ServeJSON()
	}
}
func (c *UserController) Del() {
	id, _ := c.GetInt("id")
	err := models.DB.Debug().Delete(&models.User{}, id).Error
	if err != nil {
		res := Msg{
			Code: 0,
			Msg:  "删除失败",
			Data: nil,
		}
		c.Data["json"] = res
		c.ServeJSON()
	} else {
		res := Msg{
			Code: 200,
			Msg:  "删除成功",
			Data: nil,
		}
		c.Data["json"] = res
		c.ServeJSON()
	}
}
